﻿using BusinessLogicLayer;
using IBusinessLogicLayer;
using Model;
using Model.Extend_Model;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace One.Test.MVC.Controllers
{
    /// <summary>
    ///  管理员的控制器
    /// </summary>
    public class AdminController : Controller
    {

        public void SessionName()
        {
            //获取登录人的用户编号
            var userId = Session["userId"];
            IAdminTableBusinessLogicLayer Sys = new AdminTableBusinessLogicLayer();
            List<Admin_Extend> AdminList = Sys.GetAdminList();
            SqlParameter[]
                       Parameter = new SqlParameter[]{
                            new SqlParameter("@Id",userId)
                           };

            Admin_Extend admin = AdminList.FirstOrDefault();
            Session["realname"] = admin.Name;
        }

        #region 管理员信息相关页面
        /// <summary>
        ///  管理员主页
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            return View();
        }
        /// <summary>
        ///  管理员首页
        /// </summary>
        /// <returns></returns>
        public ActionResult Welcome()
        {
            return View();
        }

        /// <summary>
        ///  管理员 -- 个人信息
        /// </summary>
        /// <returns></returns>
        public ActionResult userMessage()
        {
            //获取登录人的用户编号
            var userId = Session["userId"];
            IAdminTableBusinessLogicLayer Sys = new AdminTableBusinessLogicLayer();
            List<Admin_Extend> AdminList = Sys.GetAdminList();
            SqlParameter[]
                       Parameter = new SqlParameter[]{
                            new SqlParameter("@Id",userId)
                           };

            Admin_Extend admin = AdminList.FirstOrDefault();
            Session["realname"] = admin.Name;
            return View(admin);
        }
        #endregion

        #region 题库管理
        /// <summary>
        ///  题库管理 -- 题库列表
        /// </summary>
        /// <returns></returns>
        public ActionResult QuestionBankList()
        {
            return View();
        }
        /// <summary>
        ///  题库管理 -- 添加
        /// </summary>
        /// <returns></returns>
        public ActionResult QuestionBankAdd()
        {
            return View();
        }
        #endregion

        #region 组卷策略管理
        /// <summary>
        ///  组卷策略管理 -- 列表页
        /// </summary>
        /// <returns></returns>
        public ActionResult TacticList()
        {
            var tacticName = Request["tacticName"];
            ITacticBusinessLogicLayer tactic = new TacticBusinessLogicLayer();
            SqlParameter[]
                        Parameter = new SqlParameter[]{
                            new SqlParameter("@TacticName",tacticName)
                           };
            List<Tactic> TacticList = tactic.Getlist<Tactic>(Parameter);
            return View(TacticList);
        }
        /// <summary>
        ///  组卷策略管理 -- 新建组卷策略
        /// </summary>
        /// <returns></returns>
        public ActionResult TacticAdd()
        {
            return View();
        }

        /// <summary>
        /// 执行组卷策略添加
        /// </summary>
        /// <returns></returns>
        public bool TacticAddDo()
        {
            var tacticName = Request["tacticName"];
            var sumScore = Request["sumScore"];
            var duration = Request["duration"];
            var radioNum = Request["radioNum"];
            var radioScore = Request["radioScore"];
            var checkNum = Request["checkNum"];
            var checkScore = Request["checkScore"];
            var judgeNum = Request["judgeNum"];
            var judgeScore = Request["judgeScore"];
            SessionName();
            //获取创建人姓名
            var createPerson = Session["realname"];
            var createTime = DateTime.Now;

            Tactic tac = new Tactic();
            tac.TacticName = tacticName;
            tac.SumScore = double.Parse(sumScore);
            tac.Duration = duration;
            tac.RadioNumber = int.Parse(radioNum);
            tac.RadioScore = double.Parse(radioScore);
            tac.CheckNumber = int.Parse(checkNum);
            tac.CheckScore = double.Parse(checkScore);
            tac.JudgeNumber = int.Parse(judgeNum);
            tac.JudgeScore = double.Parse(judgeScore);
            tac.CreatePerson = createPerson.ToString();
            tac.CreateTime = createTime;
            ITacticBusinessLogicLayer tactic = new TacticBusinessLogicLayer();
            var result = tactic.ToAddSQL(tac);
            return result;
        }
        #endregion

        #region 试卷管理
        /// <summary>
        ///  试卷管理 -- 试卷列表页
        /// </summary>
        /// <returns></returns>
        public ActionResult QuestionPaperList()
        {
            return View();
        }
        #endregion

        #region 学生、教师信息管理
        /// <summary>
        ///  讲师信息列表页
        /// </summary>
        /// <returns></returns>
        public ActionResult teacherList()
        {
            ITeacher_ExtendBusinessLogicLayer Teacher = new Teacher_ExtendBusinessLogicLayer();
            List<Teacher_Extend> TeacherList = Teacher.GetTeacherList();
            return View(TeacherList);
        }

        /// <summary>
        ///  学生信息列表页
        /// </summary>
        /// <returns></returns>
        public ActionResult studentList()
        {
            IStudent_ExtendBusinessLogicLayer Student = new Student_ExtendBusinessLogicLayer();
            List<Student_Extend> StudentList = Student.GetStudentList();
            return View(StudentList);
        }

        /// <summary>
        ///  初始化添加信息视图
        /// </summary>
        /// <returns></returns>
        public ActionResult userAdd()
        {
            return View();

        }
        #endregion

        #region 数据导入
        /// <summary>
        /// 导入
        /// </summary>
        /// <param name="myfile"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Import(HttpPostedFileBase myfile)
        {
            if (myfile == null)
            {
                return Content("<script>alert('请选择文件');location.href='/Home/userAdd'</script>");
            }
            myfile.SaveAs(Server.MapPath("/File/" + myfile.FileName));
            string fileurl = "/File/" + myfile.FileName;
            DataTable dt = this.ImportExcel(fileurl);

            ITeacherBusinessLogicLayer Student = new TeacherBusinessLogicLayer();
            bool StudentAdd = Student.TeacherAdd(dt);

            return View("Index1");
        }

        #region 导入Excel所需要的方法
        public DataTable ImportExcel(string filepath)
        {
            HSSFWorkbook hssfworkbook;
            try
            {
                using (FileStream file = new FileStream(Server.MapPath(filepath), FileMode.Open, FileAccess.Read))
                {
                    hssfworkbook = new HSSFWorkbook(file);
                }
            }
            catch (Exception)
            {

                throw;
            }
            NPOI.SS.UserModel.ISheet sheet = hssfworkbook.GetSheetAt(0);
            DataTable dt = new DataTable();
            IRow headerrow = sheet.GetRow(0);
            int cellCount = headerrow.LastCellNum;
            int rowcount = sheet.LastRowNum;
            for (int i = headerrow.FirstCellNum; i < cellCount; i++)
            {
                DataColumn column = new DataColumn(headerrow.GetCell(i).StringCellValue);
                dt.Columns.Add(column);
            }
            for (int i = sheet.FirstRowNum + 1; i < rowcount; i++)
            {
                IRow row = sheet.GetRow(i);
                DataRow dataRow = dt.NewRow();
                if (row != null)
                {
                    for (int j = row.FirstCellNum; j < cellCount; j++)
                    {
                        if (row.GetCell(j) != null)
                            dataRow[j] = GetCellValue(row.GetCell(j));
                    }
                }
                dt.Rows.Add(dataRow);
            }
            GC.Collect();
            return dt;
            
        }
        private static string GetCellValue(ICell cell)
        {
            if (cell == null)
            {
                return string.Empty;
            }
            switch (cell.CellType)
            {
                case CellType.Blank:
                    return string.Empty;

                case CellType.Boolean:
                    return cell.BooleanCellValue.ToString();

                case CellType.Error:
                    return cell.ErrorCellValue.ToString();

                case CellType.Numeric:


                case CellType.Unknown:

                default:
                    return cell.ToString();
                case CellType.String:
                    return cell.StringCellValue;
                case CellType.Formula:
                    try
                    {
                        HSSFFormulaEvaluator e = new HSSFFormulaEvaluator(cell.Sheet.Workbook);
                        e.EvaluateInCell(cell);
                        return cell.ToString();
                    }
                    catch (Exception e)
                    {
                        return cell.NumericCellValue.ToString();
                    }
            }
            GC.Collect();
        }
        #endregion
        #endregion

        #region 班级管理
        /// <summary>
        ///  班级列表
        /// </summary>
        /// <returns></returns>
        public ActionResult classList()
        {
            IClass_ExtendBusinessLogicLayer Sys = new Class_ExtendBusinessLogicLayer();
            List<Class_Extend> ClassList = Sys.GetClassList();
            return View(ClassList);
        }
        #endregion
    }
}
